59E - Shortest Path - CodeForces Solution


graphs shortest paths *2000

Please click on ads to support us..

C++ Code:

#include<iostream>
#include<set>
#include<queue>
#include<map>
#include<utility>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<string.h>
using namespace std;
#define int long long
const int INF=1e15;
const int mod=1e9 + 7;
int gcd(int a, int b)
{
	if (a == 0)
		return b;
	return gcd(b % a, a);
}
const int N=3001;
set<pair<int,int> >  bad[3001];
vector<int> adj[N];
void solve(){
	int n,m,k;
	cin>>n>>m>>k;
	for(int i=0;i<m;i++){
		int a,b;
		cin>>a>>b;
		adj[a].push_back(b);
		adj[b].push_back(a);
	}
	for(int i=0;i<k;i++){
		int a,b,c;
		cin>>a>>b>>c;
		bad[c].insert(make_pair(a,b));
	}

	int p[n+1][n+1];

	p[1][1]=0;
	bool flag =0;
	vector<vector<int> > d(n+1,vector<int> (n+1,-1));
	d[1][1]=0;
	queue<pair<int,int> > q;
	pair<int,int> ans;
	q.push(make_pair(1,1));
	while(!q.empty()){
		pair<int,int> u=q.front();
		q.pop();
		if(u.second==n){
			flag=1;
			ans=u;
			break;
		}
		for(int v : adj[u.second]){
			if(bad[v].count(u)!=0){
				continue;
			}
			if(d[u.second][v]==-1){
				d[u.second][v]=d[u.first][u.second]+1;
				p[u.second][v]=u.first;
				q.push(make_pair(u.second,v));
			}
		}
	}
	if(!flag){
		cout<<-1<<endl;
		return;
	}
	cout<<d[ans.first][ans.second]<<endl;
	vector<int> aa;
	int v=n;
	int pp=ans.first;
	while(v!=1){
		aa.push_back(v);
		v=pp;
		pp=p[pp][aa[aa.size()-1]];
	}
	reverse(aa.begin(),aa.end());
	cout<<1<<" ";
	for(int x : aa){
		cout<<x<<" ";
	}
}
signed main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int t=1;
	// cin>>t;
	while(t--){
		solve();
	}
}


Comments

Submit
0 Comments
More Questions

1528B - Kavi on Pairing Duty
339B - Xenia and Ringroad
189A - Cut Ribbon
1182A - Filling Shapes
82A - Double Cola
45A - Codecraft III
1242A - Tile Painting
1663E - Are You Safe
1663D - Is it rated - 3
1311A - Add Odd or Subtract Even
977F - Consecutive Subsequence
939A - Love Triangle
755A - PolandBall and Hypothesis
760B - Frodo and pillows
1006A - Adjacent Replacements
1195C - Basketball Exercise
1206A - Choose Two Numbers
1438B - Valerii Against Everyone
822A - I'm bored with life
9A - Die Roll
1430B - Barrels
279B - Books
1374B - Multiply by 2 divide by 6
1093B - Letters Rearranging
1213C - Book Reading
1468C - Berpizza
1546B - AquaMoon and Stolen String
1353C - Board Moves
902A - Visiting a Friend
299B - Ksusha the Squirrel